import {defineStore} from 'pinia'
import {
    getAllSongs,
    getSongDetail,
    getAllPlaylists,
    getPlaylistDetail,
    getPlayHistory,
    reportPlay
} from '@/api/index.js'

export const useSongStore = defineStore('song', {
    state: () => ({
        songs: [],
        currentSong: null,
        isLoading: false,
        error: null
    }),
    getters: {
        // 获取所有歌曲
        allSongs: (state) => state.songs,
        // 获取当前播放歌曲
        nowPlaying: (state) => state.currentSong,
        // 根据ID获取歌曲
        getSongById: (state) => (id) => state.songs.find(song => song.id === id)
    },
    actions: {
        // 获取所有歌曲
        async fetchAllSongs() {
            this.isLoading = true
            try {
                const response = await getAllSongs()
                this.songs = response.data
                this.error = null
            } catch (err) {
                this.error = err.message || '获取歌曲列表失败'
                console.error('Error fetching songs:', err)
            } finally {
                this.isLoading = false
            }
        },

        // 获取歌曲详情
        async fetchSongDetail(id) {
            this.isLoading = true
            try {
                const response = await getSongDetail(id)
                // 更新歌曲列表中的信息
                const index = this.songs.findIndex(song => song.id === id)
                if (index !== -1) {
                    this.songs[index] = response.data
                } else {
                    this.songs.push(response.data)
                }
                this.error = null
                return response.data
            } catch (err) {
                this.error = err.message || '获取歌曲详情失败'
                console.error(`Error fetching song detail ${id}:`, err)
                throw err
            } finally {
                this.isLoading = false
            }
        },

        // 设置当前播放歌曲
        setCurrentSong(song) {
            this.currentSong = song
        },

        // 清空当前播放歌曲
        clearCurrentSong() {
            this.currentSong = null
        }
    }
})


export const usePlaylistStore = defineStore('playlist', {
    state: () => ({
        playlists: [],
        currentPlaylist: null,
        isLoading: false,
        error: null
    }),
    getters: {
        // 获取所有歌单
        allPlaylists: (state) => state.playlists,
        // 获取当前查看的歌单
        nowViewing: (state) => state.currentPlaylist,
        // 根据ID获取歌单
        getPlaylistById: (state) => (id) => state.playlists.find(playlist => playlist.id === id)
    },
    actions: {
        // 获取所有歌单
        async fetchAllPlaylists() {
            this.isLoading = true
            try {
                const response = await getAllPlaylists()
                this.playlists = response.data
                this.error = null
            } catch (err) {
                this.error = err.message || '获取歌单列表失败'
                console.error('Error fetching playlists:', err)
            } finally {
                this.isLoading = false
            }
        },

        // 获取歌单详情
        async fetchPlaylistDetail(id) {
            this.isLoading = true
            try {
                const response = await getPlaylistDetail(id)
                // 更新歌单列表中的信息
                const index = this.playlists.findIndex(playlist => playlist.id === id)
                if (index !== -1) {
                    this.playlists[index] = response.data
                } else {
                    this.playlists.push(response.data)
                }
                this.currentPlaylist = response.data
                this.error = null
                return response.data
            } catch (err) {
                this.error = err.message || '获取歌单详情失败'
                console.error(`Error fetching playlist detail ${id}:`, err)
                throw err
            } finally {
                this.isLoading = false
            }
        },

        // 设置当前查看的歌单
        setCurrentPlaylist(playlist) {
            this.currentPlaylist = playlist
        },

        // 清空当前查看的歌单
        clearCurrentPlaylist() {
            this.currentPlaylist = null
        }
    }
})


export const useSongHistoryStore = defineStore('history', {
    state: () => ({
        playHistory: [],
        isLoading: false,
        error: null
    }),
    getters: {
        // 获取播放历史
        history: (state) => state.playHistory,
        // 获取最近播放的歌曲
        recentPlays: (state) => state.playHistory.slice(0, 5)
    },
    actions: {
        // 获取播放历史
        async fetchPlayHistory() {
            this.isLoading = true
            try {
                const response = await getPlayHistory()
                this.playHistory = response.data
                this.error = null
            } catch (err) {
                this.error = err.message || '获取播放历史失败'
                console.error('Error fetching play history:', err)
            } finally {
                this.isLoading = false
            }
        },

        // 上报播放行为
        async reportPlay(songId) {
            try {
                await reportPlay(songId)
                // 更新本地历史记录
                const playedSong = this.playHistory.find(item => item.song.id === songId)
                if (playedSong) {
                    playedSong.play_count += 1
                    playedSong.last_played = new Date().toISOString()
                } else {
                    // 如果是新播放的歌曲，添加到历史记录
                    // 注意：这里假设API返回了完整的歌曲信息
                    // 实际情况可能需要从songStore获取歌曲详情
                    this.playHistory.unshift({
                        song: {id: songId},
                        play_count: 1,
                        last_played: new Date().toISOString()
                    })
                }
            } catch (err) {
                console.error(`Error reporting play for song ${songId}:`, err)
                throw err
            }
        }
    }
})